package com.share.two.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class Server {

	public static void main(String[] args) throws Exception {
		ServerSocketChannel ssChannel = ServerSocketChannel.open();
		ssChannel.configureBlocking(false);
		ssChannel.bind(new InetSocketAddress(12345));

		ByteBuffer buffer = ByteBuffer.allocate(1024);

		Selector selector = Selector.open();

		ssChannel.register(selector, SelectionKey.OP_ACCEPT);

		while (selector.select() > 0) {
			Iterator<SelectionKey> it = selector.selectedKeys().iterator();
			while (it.hasNext()) {
				SelectionKey sKey = it.next();
				if (sKey.isAcceptable()) {
					SocketChannel sChannel = ssChannel.accept();
					sChannel.configureBlocking(false);
					sChannel.register(selector, SelectionKey.OP_READ);
				} else if (sKey.isReadable()) {
					SocketChannel sChannel = (SocketChannel) sKey.channel();
					//sChannel.configureBlocking(false);
					sChannel.read(buffer);
					buffer.flip();
					System.out.println("server " + new String(buffer.array(), 0, buffer.remaining()));
					//buffer.clear();

				}
			}
			it.remove();
		}

	}

}
